package filterMusic.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter extends HttpFilter {

	private String sessionKey;
	private String uncheckedUrls;
	private String rediretUrl;
	
	protected void init(){
		
		ServletContext servletContext=getFilterConfig().getServletContext();
		sessionKey=servletContext.getInitParameter("sessionKey");
		uncheckedUrls=servletContext.getInitParameter("uncheckedUrls");
		rediretUrl=servletContext.getInitParameter("rediretUrl");
	}
	
	@Override
	public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		String servletPath=request.getServletPath();
		
		List<String> urls=Arrays.asList(uncheckedUrls.split(","));
		if(urls.contains(servletPath)){
			filterChain.doFilter(request, response);
			return;
		}
		
		Object user=request.getSession().getAttribute(sessionKey);
		if(user==null){
			response.sendRedirect(request.getContextPath()+rediretUrl);
			return;
		}
		filterChain.doFilter(request, response);
		
				
	}

   
}
